extends Node2D

@export var world_size: Vector2i = Vector2i(1200, 1200)  # 铺设区域大小（运行时按视口更新）
@export var tile_size: int = 64                          # 单块瓷砖边长
@export var base_color: Color = Color(0.18, 0.18, 0.2)
@export var alt_color: Color = Color(0.16, 0.16, 0.18)
@export var grout_color: Color = Color(0.08, 0.08, 0.1)  # 缝隙颜色
@export var grout_width: int = 2                          # 缝隙宽度（像素）
@export var noise_strength: float = 0.06                 # 颜色噪声强度
@export var pattern_size: int = 128                      # 小纹理尺寸（像素），会循环平铺

@onready var sprite: Sprite2D = Sprite2D.new()
var _spawn_timer: float = 0.0
var _spawning_enabled: bool = true

func _ready():
	add_child(sprite)
	# 放在 Background 之上，但低于后续节点（玩家/敌人会在其后绘制）
	z_index = 0
	sprite.z_index = 0
	# 监听视口变化
	get_viewport().size_changed.connect(_on_viewport_resized)
	_world_size_from_viewport()
	# 仅生成一次小纹理，后续重复平铺，避免大图卡顿
	_generate_pattern_texture()
	_update_sprite_region()

func spawn_enemy_with_warning(pos: Vector2) -> void:
	var indicator_script := load("res://scripts/world/spawn_indicator.gd")
	if indicator_script == null:
		return
	var ind: Node2D = indicator_script.new()
	add_child(ind)
	ind.global_position = pos

func _on_viewport_resized():
	_world_size_from_viewport()
	_update_sprite_region()

func _world_size_from_viewport():
	var vp: Vector2 = get_viewport_rect().size
	world_size = Vector2i(int(vp.x) * 2, int(vp.y) * 2)

func _generate_pattern_texture():
	var size_px: int = max(32, pattern_size)
	# 生成2×2块棋盘，保证交替色重复无缝
	var img: Image = Image.create(size_px, size_px, false, Image.FORMAT_RGBA8)
	for y in range(size_px):
		var tile_y: int = int(floor(float(y) / float(tile_size))) % 2
		var in_grout_y: bool = (y % tile_size) < grout_width or (y % tile_size) > tile_size - grout_width
		for x in range(size_px):
			var tile_x: int = int(floor(float(x) / float(tile_size))) % 2
			var in_grout_x: bool = (x % tile_size) < grout_width or (x % tile_size) > tile_size - grout_width
			if in_grout_x or in_grout_y:
				img.set_pixel(x, y, grout_color)
				continue
			var use_alt: bool = ((tile_x + tile_y) % 2) == 1
			var c: Color = alt_color if use_alt else base_color
			var n: float = _hash_noise(x, y)
			var delta: float = (n - 0.5) * 2.0 * noise_strength
			var noisy: Color = Color(clamp(c.r + delta, 0.0, 1.0), clamp(c.g + delta, 0.0, 1.0), clamp(c.b + delta, 0.0, 1.0), 1.0)
			img.set_pixel(x, y, noisy)

	var tex: ImageTexture = ImageTexture.create_from_image(img)
	sprite.texture = tex
	sprite.centered = false
	sprite.texture_repeat = CanvasItem.TEXTURE_REPEAT_ENABLED
	sprite.region_enabled = true

func _update_sprite_region():
	# 根据当前world_size设置重复区域，并把原点居中
	sprite.region_rect = Rect2(Vector2.ZERO, Vector2(world_size))
	sprite.position = Vector2(-world_size.x * 0.5, -world_size.y * 0.5)

func _process(delta: float) -> void:
	_spawn_timer += delta
	if _spawning_enabled and _spawn_timer >= 1.0:
		_spawn_timer = 0.0
		if randf() < 0.5:
			_attempt_spawn_wave()

func set_spawning_enabled(enabled: bool) -> void:
	_spawning_enabled = enabled

func _attempt_spawn_wave() -> void:
	# 50%/30%/20% -> 1/2/3个
	var r := randf()
	var count := 1
	if r > 0.5 and r <= 0.8:
		count = 2
	elif r > 0.8:
		count = 3
	# 以玩家为参考：在半径800以内且距离>150的随机位置
	var player := get_tree().get_first_node_in_group("player")
	if player == null:
		return
	var ang := randf() * TAU
	var radius := randf_range(150.0, 800.0)
	var center := (player as Node2D).global_position + Vector2.RIGHT.rotated(ang) * radius
	# 生成聚堆但不重叠的点（简单圆形分布）
	var spacing := 28.0
	for i in range(count):
		var angle := TAU * float(i) / float(count)
		var pos := center + Vector2(cos(angle), sin(angle)) * spacing
		spawn_enemy_with_warning(pos)

func _hash_noise(x: int, y: int) -> float:
	var v: int = int(x) * 374761393 + int(y) * 668265263
	v = (v ^ (v >> 13)) * 1274126177
	v = (v ^ (v >> 16)) & 0x7fffffff
	return float(v) / float(0x7fffffff)
